package com.zjp.dataFormat.service;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.ListenableFutureTask;

public class TpService {


    public static void main(String[] args) {

        t1();
    }

    public static void t1() {

        ListenableFutureTask<Integer> futureTask = new ListenableFutureTask<>(() -> {
            // 模拟耗时操作
            Thread.sleep(2000);
            return 42;
        });

        // 注册回调函数
        futureTask.addCallback(new ListenableFutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                System.out.println("异步操作成功，结果为：" + result);
            }

            @Override
            public void onFailure(Throwable ex) {
                System.out.println("异步操作失败，异常信息为：" + ex.getMessage());
            }
        });

        // 创建线程池执行任务
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("ListenableFuture-");
        executor.initialize();
        executor.execute(futureTask);

        // 执行其他操作
        System.out.println("正在执行其他操作...");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭线程池
        executor.shutdown();
    }

}
